package com.smm.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;

import org.json.JSONArray;
import org.json.JSONObject;

public class OMDBapiService {

	public JSONArray splitSearch(String fileName) {
		String[] search = {};
		JSONArray resp = new JSONArray();
		search = fileName.split("[^a-zA-Z0-9]+");
		if (search.length == 0) {
			return resp;
		}
		String incremental = "";
		for (String wrd : search) {
			wrd = wrd.trim();
			incremental += " " + wrd;
			if (getOmdbSearchResponse(incremental).length() > 0) {
				resp = getOmdbSearchResponse(incremental);
			} else {
				return resp;
			}
		}
		return resp;
	}

	public JSONObject getOmdbMovieInfoResponse(String movieName) {
		try {
			InputStream is = new URL("http://www.omdbapi.com/?i=" + movieName)
					.openStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = new JSONObject(jsonText);
			is.close();
			return json;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public JSONArray getOmdbSearchResponse(String search) {
		try {
			String url = "http://www.omdbapi.com/?s="
					+ URLEncoder.encode(search, "UTF-8");
			InputStream is = new URL(url).openStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = new JSONObject(jsonText);
			JSONArray searchJson = new JSONArray();
			if (json.has("Search")) {
				searchJson = json.getJSONArray("Search");
			}
			is.close();
			return searchJson;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}

}
